import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ref } from 'vue'
export const useHistoryCuver = () => {
  const option = ref({
    color: [
      '#FC9E40',
      '#C43CC4',
      '#ffff00',
      '#ffa500',
      '#0000FF',
      '#9400d3',
      '#9f79ee',
      '#696969',
      '#ff00ff',
      '#bdb76b',
      '#cd5c5c',
      '#006400',
      '#00bfff',
      '#66cd00',
      '#8b8989',
      '#ff1493'
    ],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        bottom: 0,
        height: 20,
        moveHandleSize: 4,
        dataBackground: {
          areaStyle: {
            color: '#333',
            opacity: 0.3
          }
        }
      },
      {
        type: 'inside'
      },
      {
        type: 'slider',
        show: true,
        yAxisIndex: 0,
        filterMode: 'empty',
        height: '70%',
        showDataShadow: false,
        right: 4,
        width: 20,
        moveHandleSize: 4,
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        snap: false,
        lineStyle: {
          width: 3,
          type: 'solid',
        }
      },
      formatter: (params: any) => {
        let result = ''
        if (Array.isArray(params)) {
          params.forEach((item: any, index: number) => {
            if (index === 0) {
              result += item.data.dateMinute + '<br>'
            }
            result += item.marker + item.data.formatter + '<br>'
          })
        }
        return result
      }
    },
    legend: {
      top: '0',
      type: 'plain',
      left: 'center',
      data: [],
      textStyle: {
        color: '#00FFA7',
        fontSize: 12
      }
    },
    grid: {
      top: '35',
      left: '30',
      right: '120',
      bottom: '40'
    },
    xAxis: {
      type: 'time',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#00FFA7',
        }
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '监测值',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#00FFA7',
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#0f5741',
          }
        },
      },
      {
        type: 'value',
        name: '人数曲线',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#69f'
          }
        },
        axisLabel: {
          formatter: '{value} 人'
        }
      }
    ],
    series: [],
  })
  const showEChartData = (chartDatas) => {
    clearECharts()

    // 生成提示信息的函数
    const formatter = (data): string => {
      let s = data.cdLocation || ''

      if (isNotNull(data.cdValue)) {
        s += ' ' + data.showValue
      }

      // 不正常
      if (getString(data.cdState) !== '0') {
        s += ' ' + getString(data.cdStateName)
      }

      return s
    }

    for (let i = 0; i < chartDatas.length; i++) {
      const { data, sensorType, cdLocation, bjIndexs, bxIndexs } =
        chartDatas[i]
      // 开关的特殊处理
      option.value.legend.data.push({
        name: cdLocation
      })

      let step: boolean | 'start' = false
      let yAxisIndex = 0
      if (sensorType && sensorType.substr(0, 1) !== '0') {
        step = 'start'
        yAxisIndex = 2
        if (!option.value.yAxis.find(item => item.name === '开关量')) {
          option.value.yAxis.push({
            type: 'value',
            name: '开关量',
            offset: 60,
            splitNumber: 1,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#91CC75'
              }
            },
            axisLabel: {
              formatter: (value) => {
                return value === 1 ? '开' : '关'
              }
            }
          })
        }
      }
      if (cdLocation === '人数曲线') {
        yAxisIndex = 1
      }
      // 增加tag和初始化series
      option.value.series.push({
        type: 'line',
        name: cdLocation,
        data: [],
        color: cdLocation === '人数曲线' ? '#69f' : '',
        symbol: 'none',
        lineStyle: {
          width: 2
        },
        yAxisIndex,
        step
      })


      // 标校 报警
      if ((bjIndexs && bjIndexs.length) || (bxIndexs && bxIndexs.length)) {
        if (bjIndexs && bjIndexs.length) {
          const bjValues = bjIndexs.map((scope: [number, number]) => {
            const arr = [data[scope[0]].dateMinute]
            if (scope[1] !== undefined) {
              arr.push(data[scope[1]].dateMinute)
            } else {
              arr.push(data[scope[0]].dateMinute)
            }
            return arr
          })
          option.value.series[i].markArea = {
            itemStyle: {
              color: option.value.color[i % 15],
              opacity: 0.2
            },
            data: bjValues.map(item => {
              return [
                {
                  name: '报警',
                  label: {
                    color: option.value.color[i % 15]
                  },
                  xAxis: item[0]
                },
                {
                  xAxis: item[1]
                }
              ]
            })
          }
        }
        if (bxIndexs && bxIndexs.length) {
          const bxValues = bxIndexs.map((scope: [number, number]) => {
            const arr = [data[scope[0]].dateMinute]
            if (scope[1] !== undefined) {
              arr.push(data[scope[1]].dateMinute)
            } else {
              arr.push(data[scope[0]].dateMinute)
            }
            return arr
          })
          option.value.series[i].markArea = {
            itemStyle: {
              color: option.value.color[i % 15],
              opacity: 0.2
            },
            data: bxValues.map(item => {
              return [
                {
                  name: '标校',
                  label: {
                    color: option.value.color[i % 15]
                  },
                  xAxis: item[0]
                },
                {
                  xAxis: item[1]
                }
              ]
            })
          }
        }
      }

      for (let x = 0; x < data.length; x++) {
        const obj = data[x]
        const preObj = data[x - 1]

        if (preObj) {
          const s = dayjs(obj.dateMinute).diff(dayjs(preObj.dateMinute), 'second')
          if (s > 60) {
            for (let index = 0; index < Math.ceil(s / 60); index++) {
              const time = dayjs(obj.dateMinute).add(60, 'second').format('YYYY-MM-DD HH:mm:ss')
              option.value.series[i].data.push({
                value: [time, null],
                dateMinute: time,
                formatter: formatter(obj)
              })
            }
          }
        }
        option.value.series[i].data.push({
          value: [obj.dateMinute, obj.cdValue],
          dateMinute: obj.dateMinute,
          formatter: formatter(obj)
        })
      }
    }
    return option
  }
  const clearECharts = () => {
    if (option.value.legend) {
      option.value.legend.data = []
    }
    option.value.series = []
    return option
  }
  const isNotNull = (value: any): boolean => {
    return value !== null && value !== undefined
  }

  const getString = (value: any): string => {
    return value?.toString() || ''
  }

  function changTooltip (chartInstance: echarts.ECharts ,index: number) {
    chartInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: index
    })
  }

  return { option, showEChartData, clearECharts, changTooltip }
}